﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace IInject.Registration
{
	public class KeyedContextRegistry : RegistryBase<List<Tuple<string, RegistryContext>>>
	{
		public KeyedContextRegistry(IContainer container) : base(container)
		{
		}

		public override RegistryContext Get(Type type, string key)
		{
            if (key != null)
			{
				return Get(type).Single(r => r.Item1 == key).Item2;
			}

			return null;
		}

        public override IEnumerable<RegistryContext> GetAll(Type type, string key)
		{
			return null;
		}

		public override bool Register(Type from, RegistryContext context)
        {
			if (context.Key != null)
            {
                if (!Contains(from))
                {
                    Add(from, new List<Tuple<string, RegistryContext>>());
                }

                var list = base[from];

                if (list.Any(t => t.Item1 == context.Key))
                {
                    throw new RegistrationException(from, context.Key);
                }

                list.Add(Tuple.Create(context.Key, context));
                return true;
			}

			return false;
		}

        public override bool Register(Type from, string key, IEnumerable<RegistryContext> contexts)
		{
			return false;
		}

		public override bool Contains(Type type, string key)
		{
			return key != null && Contains(type) && Get(type).Any(t => t.Item1 == key);
		}
	}
}
